package org.swqsbssddqs.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.swqsbssddqs.shortlink.admin.common.biz.user.UserContext;
import org.swqsbssddqs.shortlink.admin.common.convention.exception.ClientException;
import org.swqsbssddqs.shortlink.admin.common.convention.exception.ServiceException;
import org.swqsbssddqs.shortlink.admin.common.convention.result.Result;
import org.swqsbssddqs.shortlink.admin.dao.entity.GroupDO;
import org.swqsbssddqs.shortlink.admin.dao.mapper.GroupMapper;
import org.swqsbssddqs.shortlink.admin.dto.req.GroupSortReqDTO;
import org.swqsbssddqs.shortlink.admin.dto.req.GroupUpdateReqDTO;
import org.swqsbssddqs.shortlink.admin.dto.resp.GroupListRespDTO;
import org.swqsbssddqs.shortlink.admin.remote.ShortLinkActualRemoteService;
import org.swqsbssddqs.shortlink.admin.remote.ShortLinkRemoteService;
import org.swqsbssddqs.shortlink.admin.remote.dto.resp.ShortLinkGroupCountQueryRespDTO;
import org.swqsbssddqs.shortlink.admin.service.GroupService;
import org.swqsbssddqs.shortlink.admin.toolkit.RandomGenerator;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static org.swqsbssddqs.shortlink.admin.common.constant.RedisCacheConstant.LOCK_GROUP_CREATE_KEY;

@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {
    @Value("${short-link.group.max-num}")
    private Integer groupMaxNum;
    private final RBloomFilter<String> gidCreateBloomFilter;
    private final RedissonClient redissonClient;
    private final ShortLinkActualRemoteService shortLinkActualRemoteService;
    private final ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() {
    };

    @Override
    public String create(String name) {
        return create(UserContext.getUsername(),name);
    }

    @Override
    public String create(String username, String name) {
        RLock lock = redissonClient.getLock(String.format(LOCK_GROUP_CREATE_KEY, username));
        lock.lock();
        try {
            //验证用户短链接分组数量是否超过最大值
            LambdaQueryWrapper<GroupDO> eq = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getUsername,username)
                    .eq(GroupDO::getDelFlag, 0);
            Long count = baseMapper.selectCount(eq);
            if(count>groupMaxNum){
                throw new ClientException(String.format("已超出最大分组数：%d", groupMaxNum));
            }

            int maxTry = 10;
            int hasTry = 0;
            String gid = null;
            while (hasTry<maxTry){
                gid = RandomGenerator.generateRandomString();
                hasTry++;
                if(!gidCreateBloomFilter.contains(gid)){
                    GroupDO groupDO = GroupDO.builder()
                            .gid(gid)
                            .name(name)
                            .username(username)
                            .build();
                    try {
                        baseMapper.insert(groupDO);
                    }catch (DuplicateKeyException e){
                        continue;
                    }
                    gidCreateBloomFilter.add(gid);
                    return gid;
                }
            }
            if(StrUtil.isBlank(gid)){
                throw new ServiceException("生成分组标识频繁");
            }
            return gid;
        }finally {
            lock.unlock();
        }


    }

    @Override
    public List<GroupListRespDTO> listGroup() {
        LambdaQueryWrapper<GroupDO> eq = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0);
        List<GroupDO> groupDOS = baseMapper.selectList(eq);
        Result<List<ShortLinkGroupCountQueryRespDTO>> listResult = shortLinkActualRemoteService.
                listGroupShortLinkCount(groupDOS.stream().map(each -> each.getGid()).toList());
        List<GroupListRespDTO> groupListRespDTOs = BeanUtil.copyToList(groupDOS, GroupListRespDTO.class);
        groupListRespDTOs.forEach(each->{
                    Optional<ShortLinkGroupCountQueryRespDTO> first = listResult.getData().stream()
                            .filter(item -> Objects.equals(item.getGid(), each.getGid()))
                            .findFirst();
                    first.ifPresent(item -> each.setShortLinkCount(first.get().getShortLinkCount()));
                });
        return groupListRespDTOs;
    }


    public void updateGroup(GroupUpdateReqDTO groupUpdateReqDTO) {
        LambdaUpdateWrapper<GroupDO> eq = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getGid, groupUpdateReqDTO.getGid());
        GroupDO groupDO = BeanUtil.copyProperties(groupUpdateReqDTO, GroupDO.class);
        baseMapper.update(groupDO,eq);
    }

    @Override
    public Boolean deleteGroup(String gid) {
        LambdaQueryWrapper<GroupDO> eq = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setDelFlag(1);
        int update = baseMapper.update(groupDO, eq);
        if(update==0){
            return false;
        }
        return true;
    }

    @Override
    public void sortGroup(List<GroupSortReqDTO> groupSortReqDTOList) {
        groupSortReqDTOList.forEach(each -> {
            LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getGid, each.getGid())
                    .eq(GroupDO::getDelFlag, 0)
                    .set(GroupDO::getSortOrder,each.getSortOrder());
            update(updateWrapper);
        });
    }

}
